<?php
// +----------------------------------------------------------------------
// | 小说系统 [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------

namespace app\common\model;

/**
* 用户模型
*/
class User extends Base{

	protected $name = "Member";
	protected $createTime = 'reg_time';
	protected $updateTime = 'last_login_time';

	protected $type = array(
		'uid'  => 'integer',
		'reg_time' => 'integer'
	);
	//追加参数
	protected $append=[
		'birthday_text',
		'schooling_text',
		'job_status_text',
		'honour_text',
		'sex_text',
		'situation_text',
		'gradation_text',
		'group_text',
		'reg_time_text',
		'last_login_time_text',
		'last_login_ip_text'
	];
	protected $insert = array('status', 'reg_time');
	protected $update = array();

	public $editfield = array(
		array('name'=>'uid','type'=>'hidden'),
		array('name'=>'username','title'=>'用户名','type'=>'readonly','help'=>''),
		//array('name'=>'group','title'=>'分组','type'=>'select','option'=>array('3'=>'渠道商','4'=>'代理商','5'=>'责任编辑','6'=>'运营编辑','7'=>'内容总编','8'=>'优化师','9'=>'文案编辑','10'=>'文案总编','99'=>'普通用户','999'=>'管理员'),'help'=>'用户分组'),
		array('name'=>'nickname','title'=>'昵称','type'=>'text','help'=>''),
		array('name'=>'password','title'=>'密码','type'=>'password','help'=>'为空时则不修改'),
		array('name'=>'sex','title'=>'性别','type'=>'select','option'=>array('0'=>'保密','1'=>'男','2'=>'女'),'help'=>''),
		array('name'=>'email','title'=>'邮箱','type'=>'text','help'=>'用户邮箱，用于找回密码等安全操作'),
		array('name'=>'qq','title'=>'QQ','type'=>'text','help'=>''),
		array('name'=>'birthday','title'=>'生日','type'=>'text','help'=>''),
		array('name'=>'schooling','title'=>'学历','type'=>'select','option'=>array('0'=>'未知','1'=>'小学','2'=>'初中','3'=>'高中','4'=>'大专','5'=>'本科','6'=>'研究生','7'=>'博士'),'help'=>''),
		array('name'=>'job_status','title'=>'工作状态','type'=>'select','option'=>array('0'=>'试用期','1'=>'录用期','2'=>'已离职'),'help'=>''),
		array('name'=>'other_skills','title'=>'其他技能','type'=>'text','help'=>''),
		array('name'=>'hobby','title'=>'擅长','type'=>'text','help'=>''),
		//array('name'=>'score','title'=>'用户积分','type'=>'text','help'=>''),
		//array('name'=>'signature','title'=>'用户签名','type'=>'textarea','help'=>''),
		array('name'=>'status','title'=>'状态','type'=>'select','option'=>array('0'=>'禁用','1'=>'启用'),'help'=>''),
		array('name'=>'province','title'=>'省','type'=>'text','help'=>''),
		array('name'=>'city','title'=>'市','type'=>'text','help'=>''),
		array('name'=>'area','title'=>'区','type'=>'text','help'=>''),
		array('name'=>'province_code','title'=>'省code','type'=>'text','help'=>''),
		array('name'=>'city_code','title'=>'市code','type'=>'text','help'=>''),
		array('name'=>'area_code','title'=>'区code','type'=>'text','help'=>''),
		array('name'=>'address','title'=>'详细地址','type'=>'text','help'=>''),
	);

	public $addfield = array(
		array('name'=>'username','title'=>'用户名','type'=>'text','help'=>'用户名会作为默认的昵称'),
		array('name'=>'password','title'=>'密码','type'=>'password','help'=>'用户密码不能少于6位'),
		array('name'=>'repassword','title'=>'确认密码','type'=>'password','help'=>'确认密码'),
		array('name'=>'email','title'=>'邮箱','type'=>'text','help'=>'用户邮箱，用于找回密码等安全操作'),
		//array('name'=>'group','title'=>'分组','type'=>'select','option'=>array('3'=>'渠道商','4'=>'代理商','5'=>'责任编辑','6'=>'运营编辑','7'=>'内容总编','8'=>'优化师','9'=>'文案编辑','10'=>'文案总编','99'=>'普通用户','999'=>'管理员'),'help'=>'用户分组'),
	);
    
	public $useredit = array(
		array('name'=>'uid','type'=>'hidden'),
		array('name'=>'nickname','title'=>'昵称','type'=>'text','help'=>''),
		array('name'=>'sex','title'=>'性别','type'=>'select','option'=>array('0'=>'保密','1'=>'男','2'=>'女'),'help'=>''),
		array('name'=>'email','title'=>'邮箱','type'=>'text','help'=>'用户邮箱，用于找回密码等安全操作'),
		array('name'=>'mobile','title'=>'联系电话','type'=>'text','help'=>''),
		array('name'=>'qq','title'=>'QQ','type'=>'text','help'=>''),
		//array('name'=>'signature','title'=>'用户签名','type'=>'textarea','help'=>''),
	);

	
	protected function setStatusAttr($value){
		return 1;
	}

	protected function setPasswordAttr($value, $data){
		return md5($value.$data['salt']);
	}

	protected function getGroupListAttr($value, $data){
		$sql = db('AuthGroupAccess')->where('uid', $data['uid'])->fetchSql(true)->column('group_id');
		return db('AuthGroup')->where('id in ('.$sql.')')->column('title', 'id');
	}
	public function getJobStatusList()
    {
        return array('0'=>'试用期','1'=>'录用期','2'=>'已离职');
    }
	public function getSexList()
    {
        return array('0'=>'未知','1'=>'男','2'=>'女');
    }
	public function getSchoolingList()
    {
        return array('0'=>'未知','1'=>'小学','2'=>'初中','3'=>'高中','4'=>'大专','5'=>'本科','6'=>'研究生','7'=>'博士');
    }
	public function getGradationList()
    {
        return array('0'=>'F0','1'=>'F1','2'=>'F2','3'=>'F3','4'=>'F4','5'=>'F5','6'=>'F6','7'=>'F7');
    }
	//表彰
	public function getHonourTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['uid']) ? $data['uid'] : '');
		$list=[];
		if(!is_null($value)){
			$honourmodel=Model('UserHonour');
			$list=$honourmodel->where(['uid'=>$value,'status'=>'1'])->limit(0,2)->select();
		}
        return isset($list) ? $list : $value;
    }
	//年龄
	public function getBirthdayTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['birthday']) ? $data['birthday'] : '');
		$array=is_null($value)?[0=>0]:explode('-',$value);
		if($array[0]<=0){
			return 0;
		}
		$date=date('Y',time());
		$year=((int)$date-(int)$array[0])+1;
        return is_numeric($year) ? $year : 0;
    }
	//学历
	public function getSchoolingTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['schooling']) ? $data['schooling'] : '');
		$list=$this->getSchoolingList();
        return isset($list[$value]) ? $list[$value] : '';
    }
	//工作状态
	public function getJobStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['job_status']) ? $data['job_status'] : '');
        $list=$this->getJobStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
	//岗位
	public function getSituationTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['situation']) ? $data['situation'] : '');
		$list='';
		if(!is_null($value)){
			$list=db('AuthGroup')->where('id',$value)->value('title');
		}
        return isset($list) ? $list : '未知岗位';
    }
	//等级
	public function getGradationTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['gradation']) ? $data['gradation'] : '');
		$list=$this->getGradationList();
        return isset($list[$value]) ? $list[$value] : '';
    }
	//部门
	public function getGroupTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['group']) ? $data['group'] : '');
		$list='';
		if(!is_null($value)){
			$list=db('AuthGroup')->where('id',$value)->value('title');
		}
        return isset($list) ? $list : '未知部门';
    }
	//性别
	public function getSexTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sex']) ? $data['sex'] : '');
        $list=$this->getSexList();
        return isset($list[$value]) ? $list[$value] : '';
    }
	//注册时间
	public function getRegTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['reg_time']) ? $data['reg_time'] : '');
		return is_numeric($value) ? date("Y-m-d", $value) : $value;
    }
	//最后登录时间
	public function getLastLoginTimeTextAttr($value, $data)
	{
		$value = $value ? $value : (isset($data['last_login_time']) ? $data['last_login_time'] : '');
		return is_numeric($value) ? date("Y-m-d", $value) : $value;
	}
	
	//最后登录时间
	public function getLastLoginIPTextAttr($value, $data)
	{
		$value = $value ? $value : (isset($data['last_login_ip']) ? $data['last_login_ip'] : '');
		return is_numeric($value) ? long2ip( $value) : $value;
	}
	/**
	* 用户登录模型
	*/
	public function login($username = '', $password = '', $type = 1){
		$map = array();
		if (\think\Validate::is($username,'email')) {
			$type = 2;
		}elseif (preg_match("/^1[34578]{1}\d{9}$/",$username)) {
			$type = 3;
		}
		switch ($type) {
			case 1:
				$map['username'] = $username;
				break;
			case 2:
				$map['email'] = $username;
				break;
			case 3:
				$map['mobile'] = $username;
				break;
			case 4:
				$map['uid'] = $username;
				break;
			case 5:
				$map['uid'] = $username;
				break;
			default:
				return 0; //参数错误
		}

		$user = $this->where($map)->find();
		if(isset($user['status']) && $user['status']){
		    /*print_r($user['password']);
		    echo "<br>";
		   print_r(md5($password.$user['salt']));die;*/
			/* 验证用户密码 */
		
			if(md5($password.$user['salt']) === $user['password']){
				$this->autoLogin($user); //更新用户登录信息
				return $user['uid']; //登录成功，返回用户ID
			} else {
				return -2; //密码错误
			}
		} else {
			return -1; //用户不存在或被禁用
		}
	}

	/**
	 * 用户注册
	 * @param  integer $user 用户信息数组
	 */
	public function register($username, $password, $repassword, $email, $isautologin = true,$avatar=false,$userinfo=array()){
		$data['username'] = $username;
		$data['salt'] = rand_string(6);
		$data['password'] = $password;
		// $data['repassword'] = $repassword;
		$data['email'] = $email;
        $data['reg_ip']   = get_client_ip(1);
		$data['os'] = getOS();
		$data['wechat_version'] = getWechatVersion();
		if(!empty($_REQUEST['group'])){
			$data['group'] = input('group');
		}else{
			$data['group'] = 99;
		}
		if(isset($_REQUEST['is_top'])){
			$data['is_top'] = input('is_top');
		}
		if(isset($_REQUEST['s_uid'])){
			$data['s_uid'] = input('s_uid');
		}
		if(isset($_REQUEST['situation'])){
			$data['situation'] = input('situation');
		}

		if($avatar){
			$data['avatar'] = $avatar;
		}
		$data['reg_time'] = time();

		if($userinfo){
			if(array_key_exists("nickname",$userinfo)){
				$data['nickname'] = $userinfo["nickname"];
			}
			if(array_key_exists("headimgurl",$userinfo)){
				$data['avatar'] =$userinfo["headimgurl"];
			}
			if(array_key_exists("track_type",$userinfo)){
				$data['track_type'] =$userinfo["track_type"];
			}
			if(array_key_exists("track_id",$userinfo)){
				$data['track_id'] =$userinfo["track_id"];
			}

			$data['pos_city'] = $userinfo["country"]."-".$userinfo["province"]."-".$userinfo["city"];
            
		}
		
		//微信公众号ID
		if(cookie('wxmpid')){
			$data['wxmpid'] = cookie('wxmpid');
		}

		//渠道/代理ID
		if(cookie('agentid')){
			$data['agentid'] = cookie('agentid');
		}
		//推广ID
		if(cookie('spreadid')){
			$data['spreadid'] = cookie('spreadid');
		}
		//关键字ID
		if(cookie('wxkeywordid')){
			$data['wxkeywordid'] = cookie('wxkeywordid');
		}
		//是否引导注册用户
		if(cookie('guide')){
			$data['is_guide'] = 1;
		}
		$data['pid'] = input('request.pid', 0);
		//是否引导关注用户
		if(cookie('is_guideattention')){
			$data['is_guideattention'] = 1;
		}
		// dump($data);exit;
		$result = $this->validate(true)->save($data);
		
		if ($result) {
			$groupdata['uid'] = $this->data['uid'];
			$data['uid'] = $this->data['uid'];
			$groupdata['group_id'] = $data['group'];
			$this->groupaccess()->save($groupdata);
			$this->extend()->save($data);
			
			//db('authGroupAccess')->save($groupdata);
			
			if ($isautologin) {
				if(array_key_exists("login_type",$userinfo)){
					$this->data['login_type'] = $userinfo['login_type'];
					$this->data['login_host'] = $userinfo['login_host'];
				}

				$this->autoLogin($this->data);
			}
			return $this->data['uid'];
		}else{
			if (!$this->getError()) {
				$this->error = "注册失败！";
			}
			return false;
		}
	}

	/**
	 * 自动登录用户
	 * @param  integer $user 用户信息数组
	 */
	public function autoLogin($user,$log=true){
		
		/* 更新登录信息 */
		if($log){
			$data = array(
				'uid'             => $user['uid'],
				'login'           => array('exp', '`login`+1'),
				'last_login_time' => time(),
				'last_login_ip'   => get_client_ip(1),
			);
			$this->where(array('uid'=>$user['uid']))->update($data);
		}
		
		$userinfo = $this->where(array('uid'=>$user['uid']))->find();
		
		/* 记录登录SESSION和COOKIES */
		
		if(array_key_exists("login_type",$user)){
			$login_host = $user['login_host'].'_is_wechatlogin';
			
			$auth = array(
				'uid'             => $userinfo['uid'],
				's_uid'             =>$userinfo['s_uid'],
				'username'        => $userinfo['username'],
				'nickname'        => $userinfo['nickname'],
				'group'        => $userinfo['group'],
				'last_login_time' => $userinfo['last_login_time'],
				$login_host=>1,
			);
			
		}else{
			$auth = array(
				'uid'             => $userinfo['uid'],
				's_uid'             =>$userinfo['s_uid'],
				'username'        => $userinfo['username'],
				'nickname'        => $userinfo['nickname'],
				'group'        => $userinfo['group'],
				'last_login_time' => $userinfo['last_login_time'],
			);
		}
		

//		if($userinfo['group']==3 || $userinfo['group']==8){//渠道商
//			$wxmpid=db('wxmp')->where('uid = '.$userinfo['uid'].' and status=1')->order('id asc')->value('id');
//			session('wxmpid',$wxmpid);
//			$webname = db('wxmp')->where('uid = '.$userinfo['uid'].' and status=1')->order('id asc')->value('webname');
//			session('webname',$webname);
//		}elseif($userinfo['group']==4){//代理商
//			$wxmpid = db('wxmp')->where(['uid'=>$userinfo['s_uid'],'status'=>1])->order('id asc')->value('id');
//			session('wxmpid',$wxmpid);
//			$webname = db('wxmp')->where(['uid'=>$userinfo['s_uid'],'status'=>1])->order('id asc')->value('webname');
//			session('webname',$webname);
//		}else{
			session('wxmpid',0);
			session('webname','');
		//}
		
		session('user_auth', $auth);
		session('user_auth_sign', data_auth_sign($auth));
	}

	public function logout(){
		session('user_auth', null);
		session('user_auth_sign', null);
	}

	public function getInfo($uid){
		$data = $this->where(array('uid'=>$uid))->find();
		return $data;
	}

	/**
	 * 修改用户资料
	 */
	public function editUser($data, $ischangepwd = false){
		if ($data['uid']) {
			if (!$ischangepwd || ($ischangepwd && $data['password'] == '')) {
				unset($data['salt']);
				unset($data['password']);
			}else{
				$data['salt'] = rand_string(6);
			}
			$result = $this->validate('member.edit')->save($data, array('uid'=>$data['uid']));
			if ($result) {
				if($data['group']){
					db('AuthGroupAccess')->where('uid',$data['uid'])->setField('group_id', $data['group']);
				}
				$this->where('uid',$data['uid'])->update(['status' =>$data['status']]);
				return true;
			}else{
				return false;
			}
		}else{
			$this->error = "非法操作！";
			return false;
		}
	}

	public function editpw($data, $is_reset = false){
		$uid = $is_reset ? $data['uid'] : session('user_auth.uid');
		if (!$is_reset) {
			
			//后台修改用户时可修改用户密码时设置为true
			$checkPassword = $this->checkPassword($uid,$data['oldpassword']);
			if (false === $checkPassword) {
				return false;
			}

			if($data['password'] !=$data['repassword']){
				$this->error = '新密码 与 确认密码不一致';
				return false;
			}
			
			$validate = $this->validate('member.password');
			
			if (false === $validate) {
				
				return false;
			}
			
		}
		
		$data['salt'] = rand_string(6);

		return $this->save($data, array('uid'=>$uid));
		
	}

	protected function checkPassword($uid,$password){
		if (!$uid || !$password) {
			$this->error = '原密码不能为空';
			return false;
		}

		$user = $this->where(array('uid'=>$uid))->find();
		
		if (md5($password.$user['salt']) == $user['password']) {
			return true;
		}else{
			$this->error = '原始密码错误！';
			return false;
		}
	}

	public function extend(){
		return $this->hasOne('MemberExtend', 'uid');
	}

	public function groupaccess(){
		return $this->hasOne('AuthGroupAccess', 'uid');
	}

    /**
     * 浏览器端用户注册
     * @param  integer $user 用户信息数组
     */
    public function llq_rege($username, $password, $repassword, $email, $isautologin = true){
        $data['username'] = $username;
        $data['salt'] =  rand_string(6);
        $data['password'] =$password;
        $data['repassword'] = $repassword;
        $data['email'] = generate_password(rand(6,10))."@qq.com";
		$data['mobile'] = $email;
		$data['reg_ip'] = get_client_ip(1);
		if($email=="agentid"){
			$data['agentid'] = 1;
		}
        if(!empty($_REQUEST['group'])){
            $data['group'] = input('group');
        }else{
            $data['group'] = 99;
        }
        if(isset($_REQUEST['s_uid'])){
            $data['s_uid'] = input('s_uid');
        }
        if(isset($_REQUEST['t_uid'])){
            $data['t_uid'] = input('t_uid');
        }
        $result = $this->save($data);
        if ($result) {
            $groupdata['uid'] = $this->data['uid'];
            $data['uid'] = $this->data['uid'];
            $groupdata['group_id'] = $data['group'];
            $this->groupaccess()->save($groupdata);
            $this->extend()->save($data);

            //db('authGroupAccess')->save($groupdata);

            if ($isautologin) {
                $this->autoLogin($this->data);
            }
            return $result;
        }else{
            if (!$this->getError()) {
                $this->error = "注册失败！";
            }
            return false;
        }
    }

	/**
	 * APP用户注册
	 * @param  integer $user 用户信息数组
	 */
	public function app_register($username, $password, $repassword, $email, $avatar = false){
		$data['mobile'] = $data['username'] = $data['nickname'] =$username;
		$data['salt'] = rand_string(6);
		$data['password'] = $password;
		$data['repassword'] = $repassword;
		$data['email'] = $email;
		$data['sourceid'] = 2;
		$data['group'] = 99;
		if($avatar){
			$data['avatar'] = $avatar;
		}
		$result = $this->validate(true)->save($data);
		
		if ($result) {
			$groupdata['uid'] = $this->data['uid'];
			$data['uid'] = $this->data['uid'];
			$groupdata['group_id'] = $data['group'];
			$this->groupaccess()->save($groupdata);
			$this->extend()->save($data);
			return $this->data;
		}else{
			return $result;
		}
	}

	/****批量注册用户*****/

	public function batch_rege($username, $password, $repassword, $other=array()){
        $data['username'] = $username;
        $data['salt'] =  rand_string(6);
        $data['password'] =$password;
        $data['repassword'] = $repassword;
        $data['email'] = generate_password(rand(6,10))."@qq.com";

		if($other){
			foreach ($other as $k=>$v){
				$data[$k] = $v;
			}
		}
        $data['group'] = 99;
        $result = $this->save($data);
        if ($result) {
            $groupdata['uid'] = $this->data['uid'];
            $data['uid'] = $this->data['uid'];
            $groupdata['group_id'] = $data['group'];
            $this->groupaccess()->save($groupdata);
            $this->extend()->save($data);
            return $result;
        }else{
            if (!$this->getError()) {
                $this->error = "注册失败！";
            }
            return false;
        }
    }
}